package Demo85;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 岛屿最大的面积
 * https://leetcode.cn/problems/ZL6zAn/description/
 */
class Solution {
    int[] dx = new int[] {0,0,1,-1};
    int[] dy = new int[] {1,-1, 0, 0};
    int m, n;
    int[][] grid;
    public int maxAreaOfIsland(int[][] grid) {
        this.grid = grid;
        m = grid.length; n = grid[0].length;
        int ret = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    ret = Math.max(floodFill(i,j), ret);
                }
            }
        }
        return ret;
    }

    private int floodFill(int i, int j) {
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] {i,j});
        grid[i][j] = 0;
        int ret = 1;
        while(!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0], b = t[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
                    q.add(new int[] {x,y});
                    grid[x][y] = 0;
                    ret++;
                }
            }
        }
        return ret;
    }
}